import { showToast } from '@/components/Toast';
import axios from 'axios';
import { setDefaults } from '../common';
import { goLogin } from './nav';

const axiosInst = axios.create();
axiosInst.defaults.baseURL = '/api/front';

axiosInst.interceptors.request.use(
  config => {
    const defaultHeaders = {
      'Content-Type': 'application/json',
      ...(sessionStorage.token
        ? { Authorization: `jwt ${sessionStorage.token}` }
        : {}),
      ...(sessionStorage.isLogin
        ? { 'X-Has-Login': sessionStorage.isLogin }
        : {}),
    };
    config.headers = config.headers || {};
    setDefaults(config.headers, defaultHeaders);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Add a response interceptor
axiosInst.interceptors.response.use(
  response => {
    return response.data;
    // return response; // ensure type infer correct, do not return response.data
  },
  error => {
    console.log('axios error:', error);
    const response = error.response;
    if (response?.status === 401) {
      const res = response.data;
      if (res.data?.action === 'LOGIN') {
        setTimeout(() => {
          goLogin(res.data?.returnUrl);
        }, 3000);
        showToast('Signin timeout, please login again');
        return Promise.reject(error);
      }
    }

    showToast(error.response?.data?.message ?? error.message);
    return Promise.reject(error);
  }
);

export const request = axiosInst;
